<template>
    <div class="left-content">
        <div class="left-title">
            <ul class="org-tree-type">
                <li :class="orgTreeType === 2 ? 'active-type' : 'noactive-type'" id="roadClick" @click="changeOrgTreeType(2)" style="width: 80px" v-if="showOrNot()">
                    <span style="position: relative;zIndex: 10"> 按道路</span>
                    <div></div>
                </li>

                <li :class="orgTreeType === 0 ? 'active-type' : 'noactive-type'" id="orgClick" @click="changeOrgTreeType(0)" style="width: 100px" v-if="showOrNot()">
                    <span style="position: relative;zIndex: 10"> 按组织分类</span>
                    <div></div>
                </li>
                <li :class="orgTreeType === 1 ? 'active-type' : 'noactive-type'" id="videoClick" @click="changeOrgTreeType(1)" style="width: 80px">
                    <span style="position: relative;zIndex: 10"> 按视频组</span>

                    <div />
                </li>
            </ul>
        </div>
        <div class="search-camera">
            <el-input v-model="cameraName" placeholder="请输入要搜索的摄像机" clearable size="small" suffix-icon="el-icon-search" style="margin-bottom: 20px" />
        </div>
        <div class="collapse-camera" @click="collapseCameraList(orgCameraOptions)">＋收起全部摄像机</div>
        <el-scrollbar>
            <el-tree style="" empty-text="正在检索..." :data="orgCameraOptions" :props="defaultProps" draggable :allow-drag="allowDrag" :allow-drop="allowDrop" node-key="number" :default-expanded-keys="expandList" render-after-expand @node-click="handleNodeClick" :render-content="renderContent" ref="orgcameratree" :filter-node-method="filterNode" @node-drag-start="dragStart">
                <!-- TODO:。。。 -->
            </el-tree>
        </el-scrollbar>
    </div>
</template>
<script>
import {
    queryOrgCameraTree,
    getVideoStream,
    getcamera,
} from '../cameramap'
import EventBus from '@/utils/eventBus'

export default {
    name: 'TreeNode',
    props: {},
    data() {
        return {
            bitStreamType: 0,
            // 树类型： 0:按组织 1:按分组 2 按道路
            orgTreeType: 2,
            // 当前选中的结点，是蓝色的
            isCurrentNode: '',
            // 树数据
            orgCameraOptions: [],
            defaultProps: {
                // children: "children",
                // label: "label"
            },
            cameraList: [],
            //4分屏
            currentScreenType: 4,
            currentBroadcastList: [],
            screenNum: { one: 1, four: 4, six: 6, nine: 9 },
            isExpand: true,
            // expandList: ["200"],
            expandList: [],
            cameraName: null,
        }
    },
    created() {
        EventBus.$on('getCurrentScreenType', this.getScreenType)
        EventBus.$on('getBroadcastList', this.getBroadcastList)
        EventBus.$on('getBitStreamType', this.getBitStreamType)
        if (this.$route.query.cameraNum) {
            this.isExpand = false
            this.expandList.push(this.$route.query.cameraNum)
        }

        var res = this.$store.state.showAllChoices
        if (res == 1) {
            this.orgTreeType = 2
        } else {
            this.orgTreeType = 1
        }
    },
    mounted() {
        this.queryOrgCameraTree()
        setInterval(this.queryOrgCameraTree, 1000 * 60 * 20) //20分钟刷新一次数据(数据半小时更新一次)
        // this.updateCameraNode();

        if (this.$route.query.cameraNum) {
            // 首页跳转过来 查看详情
            var tt = sessionStorage.getItem('orgTypeYeah')
            if (tt != null && tt != undefined && tt != '') {
                this.orgTreeType = parseInt(tt)

                var e = document.createEvent('MouseEvents')
                e.initEvent('click', true, true)

                // 点击
                setTimeout(() => {
                    if (tt == 0) {
                        // 按组织
                        document.getElementById('orgClick').dispatchEvent(e)
                    } else if (tt == 1) {
                        // 按视频
                        document.getElementById('videoClick').dispatchEvent(e)
                    } else {
                        // 按道路
                        document.getElementById('roadClick').dispatchEvent(e)
                    }
                }, 1500);
            }
        }
    },
    computed: {
        listenComponentState() { // 当某个摄像机弹窗打开时，点击单个摄像机，切换弹窗内容
            return this.$store.state.showAllChoices
        }
    },
    watch: {
        // 根据名称筛选树
        cameraName(val) {
            if (val) {
                // 快速搜索摄像机时，默认全树
                // 获取树的根结点
                if (this.treeRootNodeKey) {
                    let rootNode = this.$refs.orgcameratree.getNode(
                        this.treeRootNodeKey
                    )
                    this.handleNodeClick(rootNode.data)
                }
            }
            this.$refs.orgcameratree.filter(val)
        },
        listenComponentState: function (val, oldval) {
            console.log('监听到变化啦.....')
            console.log(this.$store.state.showAllChoices)
        },
    },
    methods: {

        showOrNot () {
            var res = this.$store.state.showAllChoices
            return res == 1
        },

        collapse(data) {
            data.forEach((item) => {
                if (item.id == -1) {
                    this.$refs.orgcameratree.store.nodesMap[
                        item.number
                    ].expanded = false
                }
                if (item.children) {
                    this.collapseCameraList(item.children)
                }
            })
        },
        collapseCameraList(data) {
            // this.isExpand = falses
            this.collapse(data)
        },
        getBitStreamType(type) {
            this.bitStreamType = type
        },
        filterNode(value, data) {
            if (!value) return true
            return data.label.indexOf(value) !== -1
        },
        getScreenType(type) {
            this.currentScreenType = this.screenNum[type]
        },
        getBroadcastList(res) {
            this.currentBroadcastList = [...res.list]
        },

        dragStart(node) {
            console.log(node)
            this.isCurrentNode = node.data.number //节点变色
            getVideoStream({
                cameraNum: node.data.number,
                videoType: this.bitStreamType,
            }).then((res) => {
                if (res.code == 200) {
                    if (typeof res.msg === 'string') {
                        let result = JSON.parse(res.msg)
                        //奇葩接口，嵌套了又一层
                        if (result.code == 200) {
                            EventBus.$emit('dragStart', {
                                result: result.videoRequestUrl[0],
                                id: node.data.id,
                            })
                        } else {
                            this.$message({
                                showClose: true,
                                message: result.msg,
                                type: 'warning',
                            })
                        }
                    }
                }
            })
        },
        allowDrag(draggingNode) {
            //只有摄像机才能拖拽
            console.log(draggingNode, 'drag')
            return (
                draggingNode.data.id == -2 &&
                draggingNode.data.pictureStatus != 2
            )
        },
        allowDrop(draggingNode) {
            return false //不允许drop
        },
        //获取视频流
        getCameraStrame(data) {
            this.$message('正在获取视频，请稍后...')
            EventBus.$emit(
                'getCamera',
                { cameraNum: data.number, videoType: this.bitStreamType },
                undefined,
                'single'
            )
            // data.number = 'e4865e3c-dc6c-11ea-8e54-801844e841ec';
        },

        changeOrgTreeType(type) {
            if (this.orgTreeType != type) {
                this.orgTreeType = type
                this.queryOrgCameraTree()
            }
        },

        queryOrgCameraTree() {
            queryOrgCameraTree({ orgTreeType: this.orgTreeType }).then(
                (response) => {
                    this.orgCameraOptions = response.data
                }
            )
        },

        // 点击树结点
        handleNodeClick(data) {
            //id=-1网关，id=-2摄像机
            console.log(data)
            this.isCurrentNode = data.number
            //点击结点后，更改树结点颜色
            if (data.id == -2) {
                if (data.pictureStatus == 2) {
                    //相机状态 1正常 2故障
                    this.$message('相机故障')
                    this.isCurrentNode = '' //不能播放的相机，不选中
                    EventBus.$emit('changeScreen', {
                        cameraNum: data.number,
                        cameraType: data.type,
                    })
                    return
                }
                this.getCameraStrame(data)
            }
            if (data.id == -3) {
                //查询当前组织下的摄像机，并轮训；通过eventBus传参去兄弟组件内进行接口请求等操作，数据量太大，不适合传参
                EventBus.$emit('getCameraList', {
                    orgTreeType: this.orgTreeType,
                    selectNodeType: data.id,
                    selectNodeNumber: data.number,
                })
            }
        },
        // 树结点过长
        ellipsis(value, len) {
            if (!value) return ''
            if (value.length > len) {
                return value.slice(0, len) + '...'
            }
            return value
        },
        //树结构：自定义样式
        renderContent(h, { node, data, store }) {
            let nodeClassName
            let camType = '' // svg 图标 暂不用
            if (data.id === -1 || data.id === -3) {
                nodeClassName = 'org-road'
            } else if (data.id === -2) {
                // 摄像机 类型
                if (data.type == '2') {
                    //球机
                    nodeClassName = 'org-qiuji'
                    camType = 'camera-qiuji'
                } else {
                    nodeClassName = 'org-qiangji'
                    camType = 'camera-qiangji'
                }
                // 摄像机状态: picture_status : 1正常2故障（近一段时间有无截图）3不稳定；不再使用online字段
                if (data.pictureStatus === '1') {
                    // 正常
                    nodeClassName += '-online'
                } else if (data.pictureStatus == '2') {
                    // 在线
                    nodeClassName += '-breakdown'
                } else {
                    // 不稳定
                    nodeClassName += '-offline'
                }
            } else {
                // 组织级
                nodeClassName = 'org-tree'
            }

            let isPlaying = this.currentBroadcastList.some(
                (item) => item && item.cameraNum == data.number
            ) //是否在当前播放列表中

            if (this.isCurrentNode == data.number || isPlaying) {
                //当前选中--蓝色，当先选中并播放中--橙色
                if (!isPlaying) {
                    return (
                        <span
                            style="font-size:14px;cursor:pointer;font-weight: 800;color:#06A2FE"
                            slot-scope="{ node, data }"
                        >
                            <svg-icon
                                class-name={nodeClassName}
                                icon-class={nodeClassName}
                            />
                            <el-tooltip content={node.label} placement="right">
                                <span style="padding-left:5px;">
                                    {node.label}
                                </span>
                            </el-tooltip>
                        </span>
                    )
                } else {
                    return (
                        <span
                            style="font-size:14px;cursor:pointer;font-weight: 800;color:#EB8001"
                            slot-scope="{ node, data }"
                        >
                            <svg-icon
                                class-name={nodeClassName}
                                icon-class={nodeClassName}
                            />
                            <el-tooltip content={node.label} placement="right">
                                <span style="padding-left:5px;">
                                    {node.label}
                                </span>
                            </el-tooltip>
                        </span>
                    )
                }
                // if (camType) {
                if (node.label.length > 0) {
                    return (
                        <span
                            style="font-size:14px;cursor:pointer;font-weight: 800;"
                            slot-scope="{ node, data }"
                            class="colorTree"
                        >
                            <svg-icon
                                class-name={nodeClassName}
                                icon-class={nodeClassName}
                            />
                            <el-tooltip content={node.label} placement="right">
                                <span style="padding-left:5px;">
                                    {node.label}
                                </span>
                            </el-tooltip>
                        </span>
                    )
                } else {
                    return (
                        <span
                            style="`font-size:14px;cursor:pointer;font-weight: 800;`"
                            slot-scope="{ node, data }"
                            class="colorTree"
                        >
                            <svg-icon
                                class-name={nodeClassName}
                                icon-class={nodeClassName}
                            />
                            <span style="padding-left:5px;">{node.label}</span>
                        </span>
                    )
                }
            } else {
                return (
                    <span style="font-size:14px;cursor:pointer;">
                        <svg-icon
                            class-name={nodeClassName}
                            icon-class={nodeClassName}
                        />
                        <span style="padding-left:5px;">{node.label}</span>
                    </span>
                )
            }
        },
        // 实时修改摄像机状态 TODO
        updateCameraNode(nodekey) {
            // let node = this.$refs.orgcameratree.getNode(nodekey);
            // console.log(node);
        },
    },
    beforeDestroy() {
        EventBus.$off('getCurrentScreenType', this.getScreenType)
        EventBus.$off('getBroadcastList', this.getBroadcastList)
        EventBus.$off('getBitStreamType', this.getBitStreamType)
    },
}
</script>
<style lang="scss" scoped>
// .broadcast {
//     color: #eb8001;
// }

.left-content {
    position: relative;
    // left: 0;
    // top: 30px;
    width: 19vw;
    height: 87vh;
    // overflow: hidden;
    background-color: rgba(8, 28, 58, 0.6);
    &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 15px;
        background: url(~@/assets/image/map-img/left-title.png) no-repeat;
        background-size: 100%;
    }
    .left-title {
        margin-top: 20px;
        text-align: center;
        // height: 50px;
        .left-title-bg {
            width: 85%;
        }
        .org-tree-type {
            margin-top: 10px;
            li {
                // margin: 0px 40px;
                display: inline-block;
                cursor: pointer;
                font-size: 16px;
                font-family: Microsoft YaHei;
                font-weight: 400;
            }
            .active-type {
                font-style: italic;
                div {
                    position: relative;
                    top: -8px;
                    left: 0;
                    width: 100%;
                    height: 8px;
                    background: url(~@/assets/image/map-img/left-orgtype-select.png)
                        no-repeat;
                    -ms-transform: skew(-60deg);
                    -moz-transform: skew(-60deg);
                    -webkit-transform: skew(-60deg);
                    -o-transform: skew(-60deg);
                }
            }
            .noactive-type {
                div {
                    position: relative;
                    top: -10px;
                    left: 0;
                    width: 100%;
                    height: 11px;
                    opacity: 0;
                    background: url(~@/assets/image/map-img/left-orgtype.png)
                        no-repeat;
                }
            }
        }
    }
    .collapse-camera {
        padding-left: 24px;
        font-size: 12px;
        cursor: pointer;
        color: #0cdd91;
    }
}
// 滚动条
::v-deep {
    .search-camera {
        margin: 10px auto;
        // width: 200px;
        width: 80%;
        height: 30px;
        input {
            font-size: 14px;
            font-family: Microsoft YaHei;
            font-weight: 400;
            color: #fff;
            background: #080f19 !important;
            border: 1px solid #06a2fe;
        }
    }
    .el-scrollbar {
        margin-top: 10px;
        height: 87%;
        padding-bottom: 10px;
        .el-scrollbar__wrap {
            overflow-x: hidden;
            // padding-left: 7px;
        }
    }
}
// el-tree
::v-deep {
    .el-tree {
        width: 130%;
        margin-top: 10px;
        margin-left: 20px;
        background-color: transparent !important;
        font-size: 14px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #fefefe;
        .blue-tree {
            color: blue;
        }
        .orange-tree {
            color: yellow;
        }
        .el-tree-node .is-expanded {
            // width:500px
        }
        .el-tree-node:focus > .el-tree-node__content {
            background-color: transparent !important;
        }
        .el-tree-node__content:hover {
            background-color: transparent !important;
        }
        .el-tree--highlight-current
            .el-tree-node.is-current
            > .el-tree-node__content {
            background-color: transparent !important;
        }
        i {
            display: inline-block;
            width: 15px;
            height: 15px;
        }
        .org-tree {
            background: url(~@/assets/image/map-img/tree-org.png) center
                no-repeat;
        }
        .org-road {
            background: url(~@/assets/image/map-img/tree-road.png) center
                no-repeat;
        }
        .org-qiangji-online {
            background: url(~@/assets/image/map-img/qiangji-normal.png) center
                no-repeat;
        }
        .org-qiangji-breakdown {
            background: url(~@/assets/image/map-img/qiangji-breakdown.png) center
                no-repeat;
        }
        .org-qiangji-offline {
            background: url(~@/assets/image/map-img/qiangji-offline.png) center
                no-repeat;
        }
        .org-qiuji-online {
            background: url(~@/assets/image/map-img/qiuji-normal.png) center
                no-repeat;
        }
        .org-qiuji-breakdown {
            background: url(~@/assets/image/map-img/qiuji-breakdown.png) center
                no-repeat;
        }
        .org-qiuji-offline {
            background: url(~@/assets/image/map-img/qiuji-offline.png) center;
        }
    }
}
</style>